package com.javafxboot.util;

import com.itextpdf.text.pdf.PdfReader;
import com.javafxboot.entity.PrintUrl;
import com.javafxboot.util.SSL;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;

import javax.net.ssl.HttpsURLConnection;
import java.awt.print.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ReversePdf {

    /**
     * 传入一个.pdf 地址
     * @param data 地址
     * @throws Exception
     */
    public static void readPdf(PrintUrl data) throws Exception {
        // 是否排序
        boolean sort = false;
        // 编码方式
        String encoding = "UTF-8";
        // 开始提取页数
        int startPage = 1;
        // 内存中存储的PDF Document
        PDDocument pdDocument = null;
        //输入流
        InputStream inputStream = null;

//        try {
        PrintWriter out = null;
        BufferedReader in = null;

        URL url = new URL(data.getUrl());
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoInput(true);
        httpUrlConn.setRequestMethod("GET");

        boolean addHttps = url.toString().startsWith("https");
        if (addHttps) {
            SSL addSSL = new SSL();
            addSSL.trustAllHosts((HttpsURLConnection) httpUrlConn);
            ((HttpsURLConnection) httpUrlConn).setHostnameVerifier(addSSL.DO_NOT_VERIFY);
            httpUrlConn.connect();
        } else {
            httpUrlConn.connect();
        }
        inputStream = httpUrlConn.getInputStream();
        pdDocument = PDDocument.load(inputStream);

        // 获取页码
        int endPage = pdDocument.getNumberOfPages();
        PDFTextStripper stripper = null;
        stripper = new PDFTextStripper();
        // 设置是否排序
        stripper.setSortByPosition(sort);
        // 设置起始页
        stripper.setStartPage(startPage);
        // 设置结束页
        stripper.setEndPage(endPage);
        PDFRenderer renderer = new PDFRenderer(pdDocument);
        /* dpi越大转换后越清晰，相对转换速度越慢 */
//                    PdfReader reader = new PdfReader("E:/imageSort");
        int pages = pdDocument.getDocumentCatalog().getPages().getCount();
        StringBuffer imgFilePath = null;

        String imgFilePathPrefix = "";
        imgFilePath = new StringBuffer();
        imgFilePath.append(imgFilePathPrefix);
        Date dNow = new Date( );
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy\\MM\\dd\\");
        imgFilePath.append(ft.format(dNow));
        imgFilePath.append(data.getOrderSn()+".pdf");
        File dstFile = new File(imgFilePath.toString());
        //目录不存在则创建
        isexitsPath(""+ft.format(dNow)+"\\pdf");
        pdDocument.save(dstFile);
        if(data.getIsPrint()){
            printFile(dstFile.getPath());
        }
//        }catch (Exception e){
//            e.printStackTrace();
//            throw new Exception("错误");
//        } finally {
//            if (inputStream != null) {
//                // 关闭输出流
//                inputStream.close();
//            }
//            if (pdDocument != null) {
//                // 关闭PDF Document
//                pdDocument.close();
//            }
//        }
    }

    /**
     * @param fileUrl		文件地址
     */
    public static void printFile(String fileUrl) throws Exception {
//        try {
        PdfReader pdfReader = new PdfReader(new FileInputStream(fileUrl));
        // 获取总页数
        int pages = pdfReader.getNumberOfPages();
        File file = new File(fileUrl);
        PDDocument document = PDDocument.load(file);
        PDFPrintable printable = new PDFPrintable(document);
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(printable);
        job.setPageable(new PDFPageable(document));
        Paper paper = new Paper();
        // 设置打印纸张大小
        paper.setSize(283,425); // 值为点 1 = 1/72 inch
        // 设置打印位置与坐标
        paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margins
        PageFormat pageFormat = new PageFormat();
        pageFormat.setOrientation(PageFormat.REVERSE_LANDSCAPE);
        pageFormat.setPaper(paper);
        Book book = new Book();
        PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.SCALE_TO_FIT);
        // 页码
        book.append(pdfPrintable, pageFormat, pages);
        job.setPageable(book);
        //设置打印份数
        job.setCopies(1);
        job.print();
//        }  catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public static void defaultPrintPDF(String filePath) throws Exception{
//        try {
        File file = new File(filePath);
        // 读取pdf文件
        PDDocument document = PDDocument.load(file);
        // 创建打印任务
        PrinterJob job = PrinterJob.getPrinterJob();
        Paper paper = new Paper();
        // 设置打印位置 坐标

        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        paper.setImageableArea(-0, -0, pageFormat.getWidth(),pageFormat.getHeight());

        job.setPageable(new PDFPageable(document));
        PDFPrintable printable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
        job.setPrintable(printable);
        // 开始打印
        job.print();
//        } catch (PrinterException | IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

    }

    public static boolean isexitsPath(String path)throws InterruptedException{
        String [] paths=path.split("\\\\");
        StringBuffer fullPath=new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            fullPath.append(paths[i]).append("\\\\");
            File file=new File(fullPath.toString());
            if(paths.length-1!=i){//判断path到文件名时，无须继续创建文件夹！
                if(!file.exists()){
                    file.mkdir();
                    System.out.println("创建目录为："+fullPath.toString());
                }
            }
        }
        File file=new File(fullPath.toString());//目录全路径
        if (!file.exists()) {
            return true;
        }else{
            return false;
        }
    }

}
